package com.tieshan.smartwindow.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.SystemClock
import androidx.lifecycle.lifecycleScope
import com.tieshan.smartwindow.BuildConfig
import com.tieshan.smartwindow.R
import com.tieshan.smartwindow.app.AppActivity
import com.tieshan.smartwindow.other.FileConfig.VersionLogPath
import com.tieshan.smartwindow.other.FileUtil
import com.tieshan.smartwindow.other.IPUtil
import kotlinx.android.synthetic.main.activity_ip.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

//每秒钟获取一次IP
@OptIn(ExperimentalStdlibApi::class)
class IpActivity : AppActivity() {
    private var ipAddress = "1"
    private val launchTime = SystemClock.elapsedRealtime()

    override fun getLayoutId(): Int {
        return R.layout.activity_ip
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        writeAppFile()
        tv_version.text = "版本名称：Version ${getAppVersion()}"
        tv_ip.text = "IP地址："
        lifecycleScope.launch {
            while (isActive) {
                if (isValidIpAddress().not()) {
                    checkIpAddress()
                }
                if(isValidIpAddress()){
                    delay(2000L)
                    toMainActivity(ipAddress)
                    return@launch
                } else if ( SystemClock.elapsedRealtime() - launchTime > 90000) {
                    toMainActivity(ipAddress)
                    return@launch
                }
                delay(1000)
            }
        }
    }

    //本地日志存储
    private fun writeAppFile() {
        val verionCode = getVerionCode()
        val versionName = getAppVersion()
//        var updateContent="修改本地心跳时间，由原1分钟记录1次改为10分钟记录一次。"
//        var updateContent="新增USB通断电切换，PIS数据获取不到重新初始化"
        val updateContent = "优化右下角时间不显示的问题"
        val updateTime = "2025年5月21日10时"
        val content =
            " 当前版本号：$verionCode \n 当前版本名称：$versionName \n 更新时间：$updateTime \n 更新内容:$updateContent"
        FileUtil.writeFile(VersionLogPath, verionCode, content)
    }


    private fun isValidIpAddress(): Boolean {
        return ipAddress.length > 2
    }

    @SuppressLint("SetTextI18n")
    private fun checkIpAddress() {
        val ip = IPUtil.getIPAddress(this@IpActivity)
        tv_ip.text = "IP地址：${ip ?: "正在获取IP"}"
        if (ip.isNullOrBlank().not()) {
            ipAddress = ip!!
        }
    }

    private fun toMainActivity(ip: String) {
        val intent = Intent(this@IpActivity, MainActivity::class.java)
        intent.putExtra("ip", ip)
        startActivity(intent)
        finish()
    }

    override fun initData() {
    }

    // 获取应用版本信息
    private fun getAppVersion(): String {
        return BuildConfig.VERSION_NAME
    }

    // 获取应用版本信息
    private fun getVerionCode(): String {
        return BuildConfig.VERSION_CODE.toString()
    }

}